package com.ytjj.qmyx.supplychain.service;

import com.github.pagehelper.PageHelper;
import com.ytjj.common.dto.mqdto.SmsDto;
import com.ytjj.qmyx.supplychain.common.api.CommonPage;
import com.ytjj.qmyx.supplychain.common.constants.QueueConstants;
import com.ytjj.qmyx.supplychain.common.enums.ReissueTypeEnums;
import com.ytjj.qmyx.supplychain.common.exception.ApiException;
import com.ytjj.qmyx.supplychain.common.model.request.ReissueLogisticsRequest;
import com.ytjj.qmyx.supplychain.common.model.response.ReissueLogisticsResponse;
import com.ytjj.qmyx.supplychain.common.utils.DateUtil;
import com.ytjj.qmyx.supplychain.mapper.ExpressDicMapper;
import com.ytjj.qmyx.supplychain.mapper.ReissueLogisticsMapper;
import com.ytjj.qmyx.supplychain.mapper.entity.YxExpressDic;
import com.ytjj.qmyx.supplychain.mapper.entity.YxReissueLogistics;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 
 * 
 * @Version: 1.0
 */
@Slf4j
@Service
public class ReissueLogisticsService {

    @Resource
    private ReissueLogisticsMapper reissueLogisticsMapper;

    @Resource
    MqProducerService mqProducerService;

    /**
     * 补发短信内容 您的订单（换货）已发货：中通快递432875939486770。点击 u3q.cn/2mgoeo 可查询订单或联系客服!
     */
    @Value("${shortSms.supplementarySms:您的订单（%s）已发货:%s。点击 %s 可查询订单或联系客服!}")
    private String supplementarySms;
    @Resource
    private ExpressDicService expressDicService;

    public CommonPage<ReissueLogisticsResponse> selectList(ReissueLogisticsRequest reissueRequest) {
        if(StringUtils.isNotEmpty(reissueRequest.getChildOrderNo())){
            String[] split = reissueRequest.getChildOrderNo().split(",");
            if(split.length > 1){
                reissueRequest.setChildOrderNos(Arrays.asList(split));
                reissueRequest.setChildOrderNo(null);
            }
        }
        PageHelper.startPage(reissueRequest.getPageNum(), reissueRequest.getPageSize());
        List<ReissueLogisticsResponse> reissueLogisticsResponses = reissueLogisticsMapper.selectList(reissueRequest);
        CommonPage page = CommonPage.restPage(reissueLogisticsResponses);
        Set<String> childOrderNoList = reissueLogisticsResponses.stream().filter(item -> !StringUtils.isEmpty(item.getChildOrderNo())).map(ReissueLogisticsResponse::getChildOrderNo).collect(Collectors.toSet());
        List<YxReissueLogistics> reissueLogistics = null;
        if (!CollectionUtils.isEmpty(childOrderNoList)) {
            reissueLogistics = reissueLogisticsMapper.selectByChildOrderNoList(new ArrayList<>(childOrderNoList));
        }
        List<YxReissueLogistics> finalReissueLogistics = reissueLogistics;
        page.setList(reissueLogisticsResponses.stream().filter(item -> StringUtils.isNotBlank(item.getChildOrderNo())).map(item ->{
            String substring = item.getChildOrderNo().substring(0, 1);
            if (substring.equals("MZ")){
                item.setOrderSource("yxyx");
            }else if (substring.equals("D")){
                item.setOrderSource("聚卖多");
            }else if (substring.equals("F")){
                item.setOrderSource("xxxx商城");
            }
            if (!CollectionUtils.isEmpty(finalReissueLogistics)) {
                List<YxReissueLogistics> reissueLogisticsList = finalReissueLogistics.stream().filter(item2 -> item2.getChildOrderNo().equals(item.getChildOrderNo())).collect(Collectors.toList());
                item.setReissueLogisticsCount(CollectionUtils.isEmpty(reissueLogisticsList) ? 0 : reissueLogisticsList.size());
            }
//            String statusDesc = item.getLogisticsReceiptTime() == null ? item.getStatusDesc() : DateUtil.dateToStr(item.getLogisticsReceiptTime()) + "   " + item.getStatusDesc();
//            item.setStatusDesc(statusDesc);
            return item;
        }).collect(Collectors.toList()));
        return page;
    }

    public Integer updateLogistics(ReissueLogisticsRequest reissueLogistics) {
        reissueLogistics.setExpressNo(reissueLogistics.getExpressNo().trim());
        reissueLogistics.setExpressCompanyNo(reissueLogistics.getExpressCompanyNo().trim());
        reissueLogistics.setStatus(2);
        reissueLogistics.setSupplementaryDay(new Date());
        if (StringUtils.isBlank(reissueLogistics.getExpressNo())) {
            throw new ApiException("补发单号不能为空！！！");
        }
        //发送补单短信
        YxReissueLogistics old = reissueLogisticsMapper.selectByPrimaryKey(reissueLogistics.getId());
        if (StringUtils.isNotBlank(old.getOldOrderNo()) &&StringUtils.isNotBlank(reissueLogistics.getExpressNo()) &&
                old.getOldOrderNo().equals(reissueLogistics.getExpressNo())) {
            throw new ApiException("补发单号不能和原单号一致！！！");
        }
        String shopId = old.getShopId();
        SmsDto smsDto = new SmsDto();
        smsDto.setType(9);
        smsDto.setPhone(old.getUserPhone());
        Integer integer = reissueLogisticsMapper.updateLogistics(reissueLogistics);
        if (old.getReissueType() ==null) {
            return integer;
        }
        String expressCompanyNo = reissueLogistics.getExpressCompanyNo();
        List<YxExpressDic> yxExpressDics = expressDicService.queryExpressDicListByExpressValue(expressCompanyNo);
        if (!CollectionUtils.isEmpty(yxExpressDics)) {
            expressCompanyNo = yxExpressDics.get(0).getExpressKey();
        }
        String logisticsStr = expressCompanyNo+ reissueLogistics.getExpressNo();
        String code = String.format(supplementarySms, ReissueTypeEnums.getMessageByCode(old.getReissueType()), logisticsStr,"%s");
        smsDto.setCode(code);
        smsDto.setChildOrderNo(old.getChildOrderNo());
        mqProducerService.sendSms(smsDto,shopId);
        return integer;
    }

    public Integer refuseStatus(Integer id) {
        return reissueLogisticsMapper.refuseStatus(id);
    }

    public Integer refuseStatusAndReason(Integer id,String reason) {
        return reissueLogisticsMapper.refuseStatusAndReason(id,reason);
    }

    public Integer refuseListStatus(List<Integer> reissueLogisticsIdList,String reason) {
        return reissueLogisticsMapper.refuseListStatus(reissueLogisticsIdList,reason);
    }
}
